package com.blog.Utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * @author 任浩
 * @version 1.0
 */
public class IpUtils {

    /**
     * 通过request获取ip地址
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        /**
         * 上面几种方式通过请求头获取ip，如果都没有获取到的话，就使用getRemoteAddr获取ip。
         */
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("127.0.0.1".equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                assert inet != null;
                ip = inet.getHostAddress();
            }
        }

        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                /**
                 * 截取第一个ip地址。
                 */
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }
}
